﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Easy.Constant;
using Easy.Extend;
using Easy.MetaData;
using Easy.Web.CMS;
using Easy.Web.CMS.MetaData;
using Easy.Web.CMS.Widget;
using Microsoft.Practices.ServiceLocation;

namespace Easy.CMS.List.Models
{
    [DataConfigure(typeof(ListWidgetMetaData)), Serializable]
    public class ListWidget:WidgetBase
    {
        public string ListId { get; set; }

        public string FormCode { get; set; }

        public string ListCode { get; set; }

        public string DetailPageUrl { get; set; }

        public bool IsPageable { get; set; }

        public int? PageSize { get; set; }
    }

    class ListWidgetMetaData : WidgetMetaData<ListWidget>
    {
        protected override void ViewConfigure()
        {
            base.ViewConfigure();

            ViewConfig(m => m.DetailPageUrl).AsTextBox().Order(NextOrder()).AddClass("select").AddProperty("data-url", Urls.SelectPage);
            ViewConfig(m => m.IsPageable).AsCheckBox().Order(NextOrder());
            ViewConfig(m=> m.PageSize).AsTextBox().Order(NextOrder());

            ViewConfig(m => m.ListCode).AsTextBox().ReadOnly().Order(NextOrder()).AddClass("select").AddProperty("data-url", Urls.SelectList);
            ViewConfig(m => m.FormCode).AsTextBox().ReadOnly().Order(NextOrder());
            ViewConfig(m => m.ListId).AsHidden();

            ViewConfig(m => m.PartialView).AsDropDownList().Order(NextOrder()).DataSource(() =>
            {
                var path = (ServiceLocator.Current.GetInstance<IApplicationContext>() as CMSApplicationContext).MapPath("~/Modules/List/Views");
                Dictionary<string, string> templates = new Dictionary<string, string>();
                Directory.GetFiles(path, "Widget.List*.cshtml").Each(f =>
                {
                    string fileName = Path.GetFileNameWithoutExtension(f);
                    templates.Add(fileName, fileName.Replace("Widget.", ""));
                });
                return templates;
            });
        }
    }
}